import os
import shutil
import argparse
from PIL import Image


def get_file_size(infile):
    f1 = os.path.getsize(infile)
    f2 = f1/float(1024)
    return f2


def thumbnail_pic(infile, rate, outfile):
    with Image.open(infile) as im:
        size = im.size
        small_size = list((s * rate for s in im.size))
        im.thumbnail(small_size,Image.ANTIALIAS)
        dir_path = os.path.dirname(outfile)
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        im.save(outfile, "jpeg")


def thumb_util_size(infile, outfile, size=500):
    s_size = get_file_size(infile)
    print(size, s_size)
    if s_size > size:
        rate = size/s_size
        thumbnail_pic(infile, rate, outfile)
    else:
        print("No need to resize, current {}".format(s_size))
        shutil.copyfile(infile, outfile)


def arg_parse():
    parser = argparse.ArgumentParser(description='''resize picture''')
    parser.add_argument('-i', '--input', required=True, help='''input file''') 
    parser.add_argument('-o', '--output', required=True, help='''Output file''')
    args = parser.parse_args()
    return args


if __name__ == "__main__":
    args = arg_parse()
    thumb_util_size(args.input, args.output)
    # thumb_util_size("awes.jpg", "./tmp/awes_small.jpg")
